<?php

namespace App\Http\Controllers;

use App\Exceptions\ParamException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 成功时的响应
     * @param array $data
     * @param string $msg
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data = [], $msg = 'success')
    {
        return response()->json([
            'status' => 1,
            'code' => 200,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 失败时的响应
     * @param array $data
     * @param string $msg
     * @return \Illuminate\Http\JsonResponse
     */
    public function error($data = [], $msg = 'error')
    {
        return response()->json([
            'status' => 0,
            'code' => 412,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 控制器验证结果
     * @param $validate
     * @throws \Throwable
     */
    protected function throwValid($validate)
    {
        $msgArr = $validate->getMessageBag()->toArray();
        throw_if($msgArr, ParamException::class, head($msgArr)[0]);
    }
}
